package com.snopy.concurrency.atomic;

import com.snopy.pojo.Banana;
import lombok.extern.slf4j.Slf4j;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author snopy
 * @version 1.0.0
 * @classname DemoUnsafe
 * @description
 * @email 77912204@qq.com
 * @date 2022/06/28 23:53
 */
@Slf4j
public class DemoUnsafe {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        Unsafe unsafe = (Unsafe) theUnsafe.get(null);
        log.info("unsafe:{}",unsafe);
        Banana banana = new Banana();
        Field weight = banana.getClass().getDeclaredField("weight");
        Field name = banana.getClass().getDeclaredField("name");
        //获取偏移量
        long weigthOffset = unsafe.objectFieldOffset(weight);
        long nameweigthOffset = unsafe.objectFieldOffset(name);
        unsafe.compareAndSwapObject(banana,weigthOffset,null,4.5);
        unsafe.compareAndSwapObject(banana,nameweigthOffset,null,"大香蕉");
        log.info("banana:{}", banana);

    }
}
